package csl.blog.server.netty.handler;

import cn.hutool.json.JSONUtil;
import csl.blog.common.base.netty.MessageBo;
import csl.blog.common.base.netty.ResponseBo;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * @author chensl
 * @date 2023-04-19 15:31:57
 * @description
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class ClientMessageHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.info("接收的信息数据={}", msg);
//        返回请求结果
        String requestUid = (String) JSONUtil.getByPath(JSONUtil.parse(msg), MessageBo.Fields.requestUid);
        ResponseBo resp = ResponseBo.builder()
                .requestUid(requestUid)
                .code(HttpStatus.OK.toString())
                .success(Boolean.TRUE)
                .message("请求成功")
                .build();
        Channel channel = ctx.channel();
        channel.writeAndFlush(JSONUtil.toJsonStr(resp));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        ResponseBo resp = ResponseBo.builder()
                .code(HttpStatus.INTERNAL_SERVER_ERROR.toString())
                .success(Boolean.FALSE)
                .build();
        if (cause instanceof IllegalArgumentException) {
            resp.setMessage(cause.getMessage());
            channel.writeAndFlush(JSONUtil.toJsonStr(resp));
            log.warn("业务异常：{}-{}", cause.getMessage(), cause);
        }
        log.error("Error Message： {}", cause.getMessage(), cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            log.info("[M]state======{}",idleStateEvent.state());
            Channel channel = ctx.channel();
            log.info("[M]channel====={}",channel);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}
